﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Flagwind.Externals.Redis.Commands
{
	[Flagwind.Services.CommandOption("count", Type = typeof(int), DefaultValue = 1)]
	public class QueueDequeueCommand : RedisCommandBase
	{
		#region 构造方法

		public QueueDequeueCommand() : base("Out")
		{
		}

		public QueueDequeueCommand(IRedisService redis) : base(redis, "Out")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length < 1)
				throw new Services.CommandException("Missing arguments.");

			var count = context.Expression.Options.GetValue<int>("count");
			var result = new List<string>(context.Expression.Arguments.Length * count);

			for(int i = 0; i < context.Expression.Arguments.Length; i++)
			{
				var queue = this.Redis.GetQueue(context.Expression.Arguments[i]);

				if(queue == null)
				{
					context.Error.WriteLine($"The '{context.Expression.Arguments[i]}' queue is not existed.");
					return null;
				}

				//打印当前队列名
				context.Output.WriteLine(Services.CommandOutletColor.Magenta, $"Dequeued entries from 'context.Expression.Arguments[i]' queue:");

				var items = queue.Dequeue(count);

				foreach(var item in items)
				{
					result.Add((string)item);
					context.Output.WriteLine(item);
				}

				context.Output.WriteLine();
			}

			return result;
		}

		#endregion
	}
}